import { defineComponent, onMounted, ref, inject, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';

import DetailTags from '../DetailTags.vue';
import './style/controlConfig.scss';

import { BatchData } from '../../interface';

export default defineComponent({
    name: 'ControlConfig',

    setup(this, props, ctx) {
        const currentItem: any = inject('currentItem');
        const currentIndex: any = inject('currentIndex');
        const route: any = useRoute();
        const routeType = computed(() => {
            // 跳转类型
            return route.query.type;
        });
        const isViewDisabled = computed(() => {
            // 查看下禁用
            return routeType.value === 'view';
        });
        /* 渲染标签 */
        const BatchLabelRef = ref();
        // 设置标签
        let currentTagIndex = 0;

        const showBatch = (i: number, tag_list: Array<any>) => {
            BatchLabelRef.value.dialogVisible = true;
            BatchLabelRef.value.title = '批量打标签';
            BatchLabelRef.value.hasConditiion = false;
            currentTagIndex = i;
            BatchLabelRef.value.chooseDataArr.splice(0, BatchLabelRef.value.chooseDataArr.length, ...tag_list);
        };
        const onSaveBatch = (val?: any) => {
            const lh = currentItem.value.options_list[currentTagIndex].tags_list?.length || 0;
            currentItem.value.options_list[currentTagIndex].tags_list.splice(0, lh, ...val.data);
        };
        const renderTags = (columns: Array<any>) => {
            return columns.map((v: any, i: number) => {
                return (
                    <div key={v.value} class="control-config-tags__item">
                        <h4>当选项为【{v.value}】打上以下标签：</h4>
                        <DetailTags
                            class={{ hidden: !currentItem.value.is_tags }}
                            v-model:tags={v.tags_list}
                            v-model:disabled={isViewDisabled.value}
                            onOpen={() => showBatch(i, v.tags_list)}
                        />
                        <el-button
                            disabled={isViewDisabled.value || !currentItem.value.is_tags}
                            onClick={() => showBatch(i, v.tags_list)}>
                            选择标签
                        </el-button>
                    </div>
                );
            });
        };
        /* 渲染标签 */

        /* 渲染规则列表 */
        const formDataSelectList: any = inject('formDataSelectList');
        const formDataMap: any = inject('formDataMap');
        const addRules = () => {
            if (currentItem.value.rules_list.length >= 20) return ElMessage.warning('最多添加20项关联规则');
            currentItem.value.rules_list.push({
                related_key: '', // 关联字段的key
                related_value: [] // 关联字段的值
            });
        };
        const removeRules = (i: number) => {
            currentItem.value.rules_list.splice(i, 1);
        };
        const handleRelatedChange = (v: any) => {
            v.related_value.splice(0, v.related_value.length);
        };
        const renderRules = (columns: Array<any>) => {
            return columns?.map((v: any, i: number) => {
                // 根据当前的选中的key拿对应的optionList
                const options_list = formDataMap.value?.get(v.related_key)?.options_list;
                // 可选关联选择框
                const BeforeSelectList = formDataSelectList.value.slice(
                    0,
                    currentIndex.value - 1 < 0 ? 0 : currentIndex.value
                ); // 当前索引之前的s
                const form_select_list = BeforeSelectList?.filter((item: any) => {
                    // 有选项内容的 & 不是当前控件
                    return !!item.options_list?.length && item.key !== currentItem.value.key;
                });

                const isDisabled = (key: string, ItemKey: string) => {
                    // 关联规则中已经选中过的 & 不是当前选中的key （好像就是这样写的吧）可能之后只有上帝才知道这是什么意思了
                    return columns.find((item: any) => ItemKey === item.related_key) && ItemKey !== key;
                };

                if (
                    !form_select_list ||
                    !form_select_list.length ||
                    !form_select_list.find(fItem => fItem.key === v.related_key)
                ) {
                    v.related_key = null;
                }

                return (
                    <div
                        key={v.name}
                        class={{ 'control-config-rule__item': true, hidden: !currentItem.value.is_rules }}>
                        <div class={'control-config-rule__title'}>
                            <span>关联规则{i + 1}:</span>
                            {!isViewDisabled.value && (
                                <span onClick={() => removeRules(i)}>
                                    <img src="/static/delete.png" />
                                </span>
                            )}
                        </div>
                        <div class="control-config-rule__card">
                            <div class="">
                                <span>选择</span>
                                <el-select
                                    class="control-config-rule__card__select"
                                    v-model={v.related_key}
                                    placeholder="请选择"
                                    disabled={isViewDisabled.value}
                                    onChange={() => handleRelatedChange(v)}>
                                    {form_select_list.map((selctItem: any) => {
                                        return (
                                            <el-option
                                                key={selctItem.id}
                                                label={selctItem.form_change_title || selctItem.form_title}
                                                value={selctItem.key}
                                                disabled={isDisabled(v.related_key, selctItem.key)}
                                            />
                                        );
                                    })}
                                </el-select>
                                <span>中，任意一个选项</span>
                            </div>
                            <div>
                                <el-checkbox-group v-model={v.related_value} disabled={isViewDisabled.value}>
                                    {options_list?.map((optItem: any) => {
                                        return (
                                            <el-checkbox
                                                key={optItem.value}
                                                label={optItem.value}
                                                value={optItem.value}
                                            />
                                        );
                                    })}
                                </el-checkbox-group>
                            </div>
                            <div>后显示当前项目</div>
                        </div>
                    </div>
                );
            });
        };
        /* 渲染规则列表 */

        return () =>
            currentItem.value.key ? (
                <>
                    <article class="control-config-list">
                        {currentItem.value.is_customer_attr == 1 && (
                            <div class="control-config-name">
                                <span>客户属性：</span>
                                {currentItem.value.form_title}
                            </div>
                        )}
                        {currentItem.value.type != 'picture' &&
                            currentItem.value.type != 'carousel' &&
                            currentItem.value.type != 'radio' &&
                            currentItem.value.type != 'rate' &&
                            currentItem.value.type != 'muti_select' && (
                                <div>
                                    <h4 class="control-config__title">文本框提示文案</h4>
                                    <el-input
                                        disabled={isViewDisabled.value}
                                        v-model={currentItem.value.form_placeholder}
                                        maxlength="50"
                                        show-word-limit
                                        placeholder="请输入"
                                    />
                                </div>
                            )}
                        <div class="control-config__attr">
                            {currentItem.value.is_customer_attr && (
                                <h4 class="control-config__title">
                                    更新客户信息字段{' '}
                                    <el-switch
                                        v-model={currentItem.value.update_customer_message}
                                        disabled={isViewDisabled.value}></el-switch>
                                    <div class="tip">客户填写的内容信息，自动同步至客户详情中</div>
                                </h4>
                            )}
                            {currentItem.value.is_customer_attr && currentItem.value.type === 'mobile' && (
                                <h4 class="control-config__title">
                                    非客户自动成为非企微客户{' '}
                                    <el-switch
                                        v-model={currentItem.value.not_customer_auto_not_weiwork}
                                        disabled={isViewDisabled.value}></el-switch>
                                    <div class="tip">非客户只要填写了【客户属性】中【手机】，自动同步至非企微列表</div>
                                </h4>
                            )}
                        </div>
                        {['select', 'radio', 'muti_select'].includes(currentItem.value.type) && (
                            <div class="control-config__tags">
                                <h4 class="control-config__title">
                                    打标签{' '}
                                    <el-switch
                                        v-model={currentItem.value.is_tags}
                                        disabled={isViewDisabled.value}></el-switch>
                                </h4>
                                {renderTags(currentItem.value.options_list)}
                            </div>
                        )}
                        {currentItem.value.type != 'picture' &&
                            currentItem.value.type != 'carousel' &&
                            currentItem.value.type != 'rate' && <el-divider />}
                        <div class="control-config__rule">
                            <h4 class="control-config__title">
                                关联题目{' '}
                                <el-switch
                                    v-model={currentItem.value.is_rules}
                                    disabled={isViewDisabled.value}
                                    onChange={() => (currentItem.value.rules_list.length = 0)}></el-switch>
                            </h4>
                            {renderRules(currentItem.value.rules_list)}
                            <el-button
                                class="add-rule-btn"
                                plain
                                disabled={isViewDisabled.value || !currentItem.value.is_rules}
                                onClick={addRules}>
                                新建规则
                            </el-button>
                        </div>
                    </article>
                    <ZwBatchLabel ref={BatchLabelRef} onSave={onSaveBatch}></ZwBatchLabel>
                </>
            ) : (
                <div class="control-config-list config-card-empty">当前未选择控件~</div>
            );
    }
});
